package luren.king.wechatlite.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import luren.king.wechatlite.Holder.MessageHolder;
import luren.king.wechatlite.activity.MessageActivity;
import luren.king.wechatlite.R;
import luren.king.wechatlite.config.Config;
import luren.king.wechatlite.pojo.Message;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MessageAdapter extends RecyclerView.Adapter<MessageHolder> {

    Context context;

    List<Message> messages;

    public MessageAdapter(Context context, List<Message> messages){
        this.context = context;
        this.messages = messages;
    }

    @NonNull
    @Override
    public MessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.message_item, null);
        MessageHolder holder = new MessageHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MessageHolder holder, int position) {
        // 从消息列表中获取指定位置的消息对象
        Message msg = messages.get(position);
        // 将消息对象的姓名设置到视图持有者的姓名控件上
        holder.Name.setText(msg.getName());
        // 将消息对象的内容设置到视图持有者的消息控件上
        holder.Message.setText(msg.getMessage());
        // 将消息对象的时间设置到视图持有者的时间控件上
        holder.Time.setText(msg.getTime());
        holder.Msg.setOnClickListener(v -> {
            LayoutInflater inflater = LayoutInflater.from(context);
            View chat = inflater.inflate(R.layout.chat_email, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("开始聊天")
                    .setView(chat);
            AlertDialog dialog = builder.create();
            dialog.show();
            EditText email = chat.findViewById(R.id.chat_email);
            Button chat_ = chat.findViewById(R.id.start_chat);
            chat_.setOnClickListener(v1 -> {
                String num = email.getText().toString();
                if (num.isEmpty())
                {
                    Toast.makeText(context, "请输入", Toast.LENGTH_LONG).show();
                    return;
                }
                else if(num.equals(Config.EMAIL)){
                    Toast.makeText(context, "您不能和自己聊天", Toast.LENGTH_LONG).show();
                    return;
                }
                View dialogView = inflater.inflate(R.layout.custom_loading_dialog, null);

                // 设置自定义背景
                dialogView.setBackgroundResource(R.drawable.dialog_background);

                // 设置Dialog的视图
                builder.setView(dialogView);

                // 创建并显示AlertDialog
                AlertDialog alertDialog = builder.create();
                alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置窗口背景透明
                alertDialog.setCancelable(false); // 禁用取消操作（例如点击外部取消）

                alertDialog.show();
                new Thread(){
                    @Override
                    public void run() {
                        try
                        {
                            OkHttpClient client = new OkHttpClient().newBuilder()
                                    .build();
                            Request request = new Request.Builder()
                                    .url(Config.DEFAULT_URL + "/contacts/loadContactDetail/" + num)
                                    .addHeader("token", Config.JWT_TOKEN)
                                    .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                                    .build();
                            Response response = client.newCall(request).execute();
                            JSONObject information = new JSONObject(response.body().string());
                            JSONArray data = information.getJSONArray("data");
                            JSONObject json = (JSONObject) data.get(0);
                            alertDialog.dismiss();
                            //在这里可以查询信息传进去
                            Intent intent = new Intent();
                            intent.setClass(context, MessageActivity.class);
                            //这里传送点击对象的唯一参数过去 所以这里就应该将唯一参数存进数据库
                            String Email = json.getString("email");
                            intent.putExtra("Email", Email);
                            intent.putExtra("Name", json.getString("nick_name"));
                            Config.WEB_SOCKET.setSender(Email);
                            context.startActivity(intent);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }.start();

            });

        });
    }




    @Override
    public int getItemCount() {
        return messages.size();
    }
}
